package com.ve.c51;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jaredrummler.android.shell.CommandResult;
import com.jaredrummler.android.shell.Shell;
import com.ve.compiler.Compiler;
import com.ve.compiler.Installer;

import java.util.ArrayList;
import java.util.List;

public class ConsoleActivity extends AppCompatActivity {
    private TextView out;
    private EditText editText;
    private Shell.Console console;
    private Button send;
    private List<String> history;

    private Installer installer;


    public void println(CharSequence text) {
        print(text + "\n");
    }

    public void print(CharSequence text) {
        out.append(text);
    }

    private void printi(String text) {
        SpannableString string = new SpannableString(text + "\n");
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#ff59c4b7"));
        string.setSpan(colorSpan, 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        out.append(string);
    }

    public void printe(CharSequence text) {
        SpannableString string = new SpannableString(text + "\n");
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#e9dd6473"));
        string.setSpan(colorSpan, 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        out.append(string);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_console);
        out = findViewById(R.id.out);
        send = findViewById(R.id.send);
        send.setOnLongClickListener(this::onSendLongClick);
        editText = findViewById(R.id.input);
        editText.setOnEditorActionListener((v, actionId, event) -> {
            onSendClick(editText);
            return true;
        });
        history = new ArrayList<>();
        console = Compiler.getCompiler().getConsole();
       /* if (hasPermission()) {
            start();
        }*/


    }

    /*private void start() {
        installer = new Installer(this);
        if (!installer.isInstalled()) {

            installer.setProgressListener(new ProgressListener.DialogProgressAdapter(this, "安装环境") {
                @Override
                public void onSucceed(String info) {
                    super.onSucceed(info);
                    Compiler compiler = new Compiler();
                    compiler.boot(ConsoleActivity.this);
                    createShell(compiler.getConsole());
                }

                @Override
                public void onFail(String reason, Exception e) {
                    super.onFail(reason, e);
                    try {
                        Shell.Console mconsole = new Shell.Console.Builder()
                                .useSH()
                                .setWatchdogTimeout(30000)
                                .build();
                        createShell(mconsole);
                    } catch (ShellNotFoundException e2) {
                        e2.printStackTrace();
                    }

                }
            });
            boolean setup = installer.setup();
            println("Setup:" + setup);
        } else {

            Compiler compiler = new Compiler();
            compiler.boot(ConsoleActivity.this);
            println("Boot " + compiler.isBooted());
            try {
                createShell(Shell.SH.getConsole());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }*/
/*

    private boolean hasPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }

        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        boolean has = true;
        for (String permission : permissions) {
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                has = false;
                break;
            }

        }
        if (!has) {
            requestPermissions(permissions, 999);
        }
        return has;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        for (int i = 0; i < permissions.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "授权失败", Toast.LENGTH_LONG).show();
                return;
            }
        }

        start();
    }

    private void createShell(Shell.Console console) {
        this.console = console;
        runOnUiThread(() -> {
            shell(String.format("export PREFIX=%s", getFilesDir().getAbsolutePath()));
            shell("export PATH=$PATH:$PREFIX");
            shell("export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PREFIX");
            shell("export HOME=$PREFIX");


        });

    }
*/


    private void showHistory() {
        new AlertDialog.Builder(ConsoleActivity.this)
                .setTitle("历史")
                .setSingleChoiceItems(new ArrayAdapter<>(ConsoleActivity.this, android.R.layout.simple_list_item_1, history), 0, (dialog, which) -> {
                    if (which >= 0) {
                        editText.setText(history.get(which));
                    }
                    dialog.cancel();
                })
                .show();
    }

    public void onSendClick(View view) {
        shell(editText.getText().toString());
    }

    public boolean onSendLongClick(View view) {
        out.setText("");
        return false;
    }

    private void shell(String cmd) {
        if (TextUtils.isEmpty(cmd)) {
            return;
        }
        if (console == null) {
            printe("console is null \n");
            return;
        }
        println("SH: " + cmd);
        editText.setText("");
        history.add(0, cmd);
        if (cmd.equals("clear")) {
            out.setText("");
            return;
        }
        CommandResult result = console.run(cmd);

        if (result.isSuccessful()) {
            printi(result.getStdout());
        } else {
            printe(result.getStderr());
        }

    }

    public void onHistoryClick(View view) {
        showHistory();
    }
}
